﻿using ExcelUnity.Exporter.Exporters;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace ExcelUnity.Exporter.Wrappers.SheetWrapperBuilders
{
    public class DataTableBuilder
    {
        public static ExportSheetWrapper? BuildExportSheetWrapper(ExportSheet exportSheet)
        {
            var colIndex = 0;
            var columns = new Dictionary<int, string>();
            foreach (DataColumn col in exportSheet.Table!.Columns)
                columns.Add(colIndex++, col.ToString());

            var exportRows = new List<ExportRowWrapper>();

            //创建title
            var rowIndex = 0;
            if (exportSheet.Title != null)
            {
                var cells = columns.Select(x => new ExportCellWrapper(x.Key, x.Key == 0 ? exportSheet.Title.Title : string.Empty)
                {
                    MergeColumn = true,
                    CellStyle = x.Key == 0 ? exportSheet.Title.Style : null
                }).ToList();
                var row = new ExportRowWrapper(cells, rowIndex++);
                exportRows.Add(row);
            }

            //创建header
            exportRows.Add(new ExportRowWrapper(columns.Select(x => new ExportCellWrapper(x.Key, false, x.Value)).ToList(), rowIndex++));

            //填充行
            for (int i = 0; i < exportSheet.Table!.Rows.Count; i++)
            {
                var cells = new List<ExportCellWrapper>();
                for (int j = 0; j < exportSheet.Table!.Columns.Count; j++)
                    cells.Add(new ExportCellWrapper(j, false, exportSheet.Table!.Rows[i][j].ToString()));

                exportRows.Add(new ExportRowWrapper(cells, rowIndex++));
            }

            var columnWrappers = columns.Select(x => new ExportColumnWrapper(x.Key, x.Value)).ToList();
            return new ExportSheetWrapper(columnWrappers, exportRows);
        }
    }
}
